<template>
    <div class="main_container">
        <div v-if="pageName=='index'">
            <el-form :model="queryParams" label-width="auto">
                <el-row>
                    <el-col :span="7">
                        <el-form-item label="收支类型:">
                            <el-select style="width: 240px;" v-model="queryParams.record_type" @change="typeChange"
                                placeholder="请选择">
                                <el-option  label="支出" :value="2"></el-option>
                                <el-option  label="收入" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="费用类型:">
                            <el-select style="width: 240px;" v-model="queryParams.category" placeholder="请选择" clearable>
                                <el-option v-for="item in typeList" :key="'type_'+item.id" 
                                    :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="支付方式:">
                            <el-select style="width: 240px;" v-model="queryParams.pay_type" placeholder="请选择" clearable>
                                <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="21">
                        <el-form-item label="支付日期:">
                            <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                                    v-model="queryParams.create_datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                                    placeholder="请选择时间区间" style="width: 240px;" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button size="small" icon="el-icon-search" @click="handleQuery"
                            style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <el-row :gutter="16" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-plus"
                    size="small"
                    @click="handleAdd"
                     v-hasPermi="['expenditure_add']"
                    >新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    :class="multiple?'btn_info_color':'btn_remove_color'"
                    size="small"
                    icon="el-icon-delete"
                    @click="handleRemoveSelect"
                    :disabled="multiple"
                     v-hasPermi="['expenditure_del']"
                    >删除所选</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-setting"
                    size="small"
                    @click="handleSetting"
                    >设置费用类型</el-button>
                </el-col>
            </el-row>
            <el-table border :data="expendList" style="margin-top: 15px;" @selection-change="handleSelectionChange" >
                <el-table-column type="selection" width="60" align="center" />
                <el-table-column label="单据编号" align="left" min-width="100" prop="corp_order_no" />
                <el-table-column label="支出类型" align="left" prop="record_typeName" />
                <el-table-column label="费用类型" align="left" prop="cateName" />
                <el-table-column label="往来单位" align="left" prop="partnerName" />
                <el-table-column v-if="queryParams.record_type===2" label="员工姓名" align="left" prop="staffName" />
                <el-table-column label="支出日期" align="left" prop="expenditure_date" />
                <el-table-column label="支付方式" align="left" prop="pay_type_display" />
                <el-table-column label="金额" align="left" prop="paid_fee" />
                <el-table-column label="经办人" align="left" prop="handlerName" />
                <el-table-column label="操作" min-width="120" align="left" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleView(scope.row)"
                            style="font-weight: bold;"
                        >查看</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleEdit(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['expenditure_update']"
                        >编辑</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleRemove(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['expenditure_del']"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="getExpendLists"
                @current-change="getExpendLists"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增页面 -->
        <common-dialog :visiable="pageName == 'addOrder'">
            <add-order :corpId="corp_id" @hidden="hidden" @success="success"></add-order>
        </common-dialog>
        <!-- 编辑页面 -->
        <common-dialog :visiable="pageName == 'editOrder'">
            <add-order :corpId="corp_id" :editId="editId" @hidden="hidden" @success="success"></add-order>
        </common-dialog>

        <!-- 查看 -->
        <el-dialog destroy-on-close :visible.sync="showExpendInfo" title="查看日常支出" append-to-body>
            <el-row>
                <el-form ref="viewForm" :model="viewForm" size="small" label-width="auto">
                    <el-col :span="12">
                        <el-form-item label="支出类型：">
                            <div>{{ viewForm.record_typeName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="费用类型：">
                            <div>{{ viewForm.cateName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="queryParams.record_type===2" label="员工姓名：">
                            <div>{{ viewForm.staffName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="往来单位：">
                            <div>{{ viewForm.partnerName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="支出日期：">
                            <div>{{ viewForm.expenditure_date }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="支付方式：">
                            <div>{{ viewForm.pay_type_display }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="支出金额：">
                            <div>{{ viewForm.paid_fee }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="经办人：">
                            <div>{{ viewForm.handlerName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <div>{{ viewForm.remark }}</div>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div slot="footer">
                <el-button @click="showExpendInfo=false">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 分类 -->
        <el-drawer
            title="设置费用类型"
            append-to-body
            :visible.sync="showCategorySet"
            :wrapperClosable="false"
            :before-close="handleClose">
            <div class="cates_view">
                <div class="tops">
                    <div class="tabs">
                        <el-radio-group v-model="radioName" size="small" @change="radioChange">
                            <el-radio-button :label="2">支出</el-radio-button>
                            <el-radio-button :label="1">收入</el-radio-button>
                        </el-radio-group>
                    </div>
                    <el-button class="btn_primary_color" icon="el-icon-plus" size="small" @click="handleAddCategory">新增费用类型</el-button>
                </div>
                <div class="list">
                    <div class="cell" v-for="item in cateList" :key="'cate_'+item.id">
                        <span>{{ item.name }}</span>
                        <div class="btns">
                            <span @click="editCategory(item)">编辑</span>
                            <span style="color: red;" @click="removeCategory(item)">删除</span>
                        </div>
                    </div>
                </div>
            </div>
        </el-drawer>
        <!-- 新增分类 -->
        <el-dialog
            :title="cateEditDialogTitle"
            :visible.sync="showCategoryAdd"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="rules">
                    <el-form-item label="费用类型:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showCategoryAdd=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addCategory">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import commonDialog from "@/components/commonDialog";
import { listExpend, removeExpend, removeBatchExpend, listExpendCategory, addExpendCategory,
    editExpendCategory, removeExpendCategory, infoExpend } from "@/api/expenses";

export default {
    name: 'expensesList',
    data() {
        return {
            showExpendInfo: false,
            showCategorySet: false,
            showCategoryAdd: false,
            cateEditDialogTitle: '',
            corp_id: '',
            editId: '',
            multiple: true,
            queryParams: {
                category: '',
                record_type: 2,
                pay_type: '',
                create_datetime: [],
                expenditure_date__lte: '',  //小于等于
                expenditure_date__gte: '',  //大于等于
            },
            pageParam: {
                page: 1,
                num: 10
            },
            pageName: 'index',
            total: 0,
            expendList: [],
            typeList: [],
            cateList: [],
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            editDialogTitle: '',
            staffLists: [],
            handlersList: [],
            viewForm: {},
            radioName: 2,
            cateInfo: {
                name: '',
                record_type: 2,
            },
            rules:{
                name: [
                    { required: true, message: "请输入费用类型", trigger: "blur" },
                ],
            },
        }
    },
    watch: {
        'queryParams.create_datetime': {
            handler(value){
                if(value){
                    this.queryParams.expenditure_date__lte = value[1]
                    this.queryParams.expenditure_date__gte = value[0]
                }
                else{
                    this.queryParams.expenditure_date__lte = this.queryParams.expenditure_date__gte = null
                }
            },
            deep: true
        },
        '$route.query.bussId3': {
            immediate: true, // 首次加载时触发
            handler(newId) {
                if (newId) {
                    this.getInfo(newId)
                }
            }
        },
        showExpendInfo: function(val) {
            if (this.$route.query.bussId3 && !val){
                this.$router.replace({ path: this.$route.path, query: {} });
            }
        }
    },
    components: {
        commonDialog,
        addOrder: () => import('./edit.vue')
    },
    created() {
        this.corp_id = this.$store.state.corpId
        this.getCategorys()
        this.getExpendLists()
    },
    methods: {
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.getExpendLists()
        },
        getInfo(id) {
            let corp = this.$store.state.corpId
            infoExpend(id, { corp }).then(res => {
                let item = res.data.data
                item.paid_fee = '￥'+item.paid_fee
                item.record_typeName = item.record_type==2?'支出':'收入'
                item.cateName = item.category_detail?item.category_detail.name:''
                item.handlerName = item.handler_user_detail?item.handler_user_detail.username:''
                if (item.cateName=='员工工资' && this.queryParams.record_type===2) {
                    item.staffName = item.staff_user_detail?item.staff_user_detail.username:''
                }else{
                    item.partnerName = item.customer_detail?item.customer_detail.name:(item.suppliers_detail?item.suppliers_detail.name:'')
                }
                this.viewForm = item
                this.showExpendInfo = true
            })
        },
        getCategorys(type) {
            let param = {
                corp: this.corp_id,
                page: 1,
                num: 999
            }
            if (type){
                param.record_type = type
            }else{
                param.record_type = this.queryParams.record_type
            }
            listExpendCategory(param).then(res => {
                if (type){
                    this.cateList = res.data.data.category_list
                }else {
                    this.typeList = res.data.data.category_list
                }
            })
        },
        typeChange() {
            this.queryParams.category = ''
            this.getCategorys()
            this.getExpendLists()
        },
        handleSetting() {
            this.getCategorys(2)
            this.showCategorySet = true
        },
        handleClose(done){
            done();
        },
        radioChange(val) {
            this.getCategorys(val)
        },
        handleAddCategory() {
            this.cateInfo.name = ''
            this.cateEditDialogTitle = '新增费用类型'
            this.showCategoryAdd = true
        },
        addCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return

                let temp = null
                that.cateInfo.corp = that.corp_id
                this.cateInfo.record_type = that.radioName
                if (that.cateInfo.id) {
                    temp = editExpendCategory(that.cateInfo.id,that.cateInfo)
                }else{
                    temp = addExpendCategory(that.cateInfo)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.cateInfo.id = ''
                        that.getCategorys(that.radioName)
                        that.showCategoryAdd = false
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        editCategory(item) {
            console.log(item)
            this.cateInfo.name = item.name
            this.cateInfo.id = item.id
            this.cateEditDialogTitle = '编辑费用类型'
            this.showCategoryAdd = true
        },
        removeCategory(item) {
            let that = this
            this.$confirm('您确定要删除该费用类型吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeExpendCategory(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.getCategorys(that.radioName)
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
         // 获取列表
        getExpendLists() {
            this.queryParams.corp = this.corp_id
            let params = Object.assign({}, this.queryParams, this.pageParam)
            listExpend(params).then(res => {
                this.expendList = res.data.data.expenditure_list.filter(item => {
                    item.paid_fee = '￥'+item.paid_fee
                    item.record_typeName = item.record_type==2?'支出':'收入'
                    item.cateName = item.category_detail?item.category_detail.name:''
                    item.handlerName = item.handler_user_detail?item.handler_user_detail.username:''
                    if (item.cateName=='员工工资' && this.queryParams.record_type===2) {
                        item.staffName = item.staff_user_detail?item.staff_user_detail.username:''
                    }else{
                        item.partnerName = item.customer_detail?item.customer_detail.name:(item.suppliers_detail?item.suppliers_detail.name:'')
                    }
                    return item
                })
                this.total = res.data.data.total
            })
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            // console.log(selection);
            this.multiple = !selection.length
            let ids = selection.map(item => item.id)
            this.selectIds = ids
        },
        // 新增
        handleAdd() {
            this.editId = null
            this.pageName = 'addOrder'
        },
        // 查看
        handleView(item) {
            this.viewForm = item
            this.showExpendInfo = true
        },
        // 编辑
        handleEdit(item) {
            this.editId = item.id
            this.pageName = 'editOrder'
        },
        // 删除所选
        handleRemoveSelect() {
            let that = this
            this.$confirm('您确定要删除选中的销售单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeBatchExpend({
                    corp_id: that.corp_id,
                    pk_id_list: that.selectIds
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 删除
        handleRemove(item) {
            let that = this
            this.$confirm('您确定要删除该日常支出吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeExpend(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        hidden(res) {
            console.log(res)
            if (res && res.isRefresh){
                this.getCategorys()
            }
            this.pageName = 'index'
        },
        success() {
            this.handleQuery()
            this.pageName = 'index'
        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .cates_view {
        padding: 0 30px 30px 30px;
        .tops {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .list {
            margin-top: 28px;
            .cell {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                font-size: 14px;
                border-bottom: 1px solid #eee;
                .btns {
                    display: inline-flex;
                    align-items: center;
                    height: 100%;
                    span {
                        width: 50px;
                        text-align: center;
                        color: @blue;
                        font-size: 13px;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }
</style>